﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Comm
{
   public class TCPHelp1
    {
        /// <summary>
        /// 16000端口
        /// </summary>
        Socket clientSocket1 = null;//客户端套接字

        public string errorStr = "";

        public delegate void FinPrint(string Mes);
        public event FinPrint finPrint;
        public string Open(string nowip, string port)
        {

            try
            {
                //建立与服务器连接的套接字                 
                IPAddress ip = IPAddress.Parse(nowip);

                //建立与服务器连接的套接字                 
                IPEndPoint iep1 = new IPEndPoint(ip, Convert.ToInt32(port));

                if (clientSocket1 == null || !clientSocket1.Connected)
                {
                    clientSocket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
                clientSocket1.SendTimeout = 500;
                clientSocket1.ReceiveTimeout = 500;
                clientSocket1.Connect(iep1);
                IsExit = false;
                Thread th = new Thread(readMes);
                th.Start();
                return "ok";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
        private void readMes()
        {
            while (!IsExit)
            {

                if (clientSocket1.Poll(100, SelectMode.SelectRead))
                {
                    Thread.Sleep(150);
                    byte[] receiveBytes = new byte[1024];
                    int successReceiveBytes = clientSocket1.Receive(receiveBytes);
                    if (successReceiveBytes > 0)
                    {
                        string mes = Encoding.UTF8.GetString(receiveBytes, 0, successReceiveBytes);
                        finPrint(mes);
                    }
                }
                Thread.Sleep(20);
            }
        }
       public bool IsExit = true;
        Thread thre = null;

        public bool sendMes(string mes)
        {
            //发送数据                     

            byte[] strbyte = System.Text.Encoding.Default.GetBytes(mes);
            byte[] writebyte = new byte[strbyte.Length + 2];
            writebyte[0] = 0x02;
            for (int i = 0; i < strbyte.Length; i++)
            {
                writebyte[i + 1] = strbyte[i];
            }
            writebyte[strbyte.Length + 1] = 0x03;
            try
            {
                int successSendBtyes = clientSocket1.Send(writebyte, writebyte.Length, SocketFlags.None);
                bool IsGet = false;
                // return true;
                DateTime delaystop = DateTime.Now.AddMilliseconds(500);
                while (delaystop > DateTime.Now)
                {
                    byte[] receiveBytes = new byte[1024];
                    if (clientSocket1.Poll(100, SelectMode.SelectRead))
                    {
                        int successReceiveBytes = clientSocket1.Receive(receiveBytes);
                        byte Fin = 0x06;
                        if (successReceiveBytes > 0 && receiveBytes.Contains(Fin))
                        {
                            IsGet = true;
                            break;
                        }

                    }
                }
                return IsGet;
            }
            catch (Exception ss)
            {
                errorStr = ss.Message;
                return false;
            }
            // return false;
        }

        public bool Close()
        {
            IsExit = true;
            Thread.Sleep(100);
            try
            {
                if (clientSocket1 != null && clientSocket1.Connected)
                {
                   // clientSocket1.Shutdown(SocketShutdown.Both);
                    clientSocket1.Close();

                }
            }
            catch (Exception ex)
            {
                WriteFileCls.InserLog(ex.Message);
                return false;
            }
            return true;
        }

    }
}

